<?php

namespace pmvc\tx;

use pmvc\log\Log;

class TransactionUtil {

	private static $TRANSACTIONS = Array();

	private static function getThreadId() {
		return "thread-1"; // TODO: better identify the current thread
	}

	public static function getTransaction() {
		$threadId = self::getThreadId();
		return (array_key_exists($threadId, self::$TRANSACTIONS))
			? self::$TRANSACTIONS[$threadId] : NULL;
	}

	public static function getOrCreateTransaction(TransactionProvider $provider, $autoCommit=FALSE) {
		$threadId = self::getThreadId();
		if (!array_key_exists($threadId, self::$TRANSACTIONS)) {
			Log::debug("Creating new JoinedTransaction");
			self::$TRANSACTIONS[$threadId] = new JoinedTransaction($provider->createTransaction());
			self::$TRANSACTIONS[$threadId]->setAutoCommit($autoCommit);
		} else {
			Log::debug("Returning existing JoinedTransaction");
		}
		return self::$TRANSACTIONS[$threadId];
	}

	public static function startTransaction(TransactionProvider $provider, $autoCommit=FALSE) {
		$tx = self::getOrCreateTransaction($provider, $autoCommit);
		$tx->start();
	}

	public static function commitTransaction() {
		$tx = self::getTransaction();
		if (isset($tx) && $tx!=NULL) {
			$tx->commit();
			if ($tx->isCommited()) {
				Log::debug("Clearing commited Transaction");
				$threadId = self::getThreadId();
				unset(self::$TRANSACTIONS[$threadId]);
			}
		}
	}

	public static function rollbackTransaction() {
		$tx = self::getTransaction();
		if (isset($tx) && $tx!=NULL) {
			$tx->rollback();
			if ($tx->isRolledBack()) {
				Log::debug("Clearing rolled back Transaction");
				$threadId = self::getThreadId();
				unset(self::$TRANSACTIONS[$threadId]);
			}
		}
	}

}
?>